package se.topshelf.golftracker.web.controller.memberclub;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import se.topshelf.golftracker.core.domain.MemberClub;
import se.topshelf.golftracker.core.domain.Player;
import se.topshelf.golftracker.core.service.BaseService;
import se.topshelf.golftracker.core.service.MemberClubService;
import se.topshelf.golftracker.web.validator.BaseEntityValidator;

import java.text.MessageFormat;

/**
 *  Validates Player entities, so that they are ok save.
 */
public class MemberClubValidator extends BaseEntityValidator<MemberClub> {

    static final String FIRST_NAME_FIELD_NAME = "firstName";
    static final String LAST_NAME_FIELD_NAME = "lastName";
    static final String HANDICAP_FIELD_NAME = "handicap";
    static final String GOLD_ID_DUPLICATE_DEFAULT_ERROR_MESSAGE = "Golf Id {0} is already assigned to other golfer.";
    static final String DUPLICATE_GOLF_ID_ERROR_CODE = "duplicateGolfId";
    static final String NAME_FIELD_NAME = "name";
    private MemberClubService memberClubService;


    public MemberClubValidator(MemberClubService memberClubService) {
        super(MemberClub.class);
        this.memberClubService = memberClubService;
    }


    @Override
    protected void validateFields(MemberClub entityToCheck, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, NAME_FIELD_NAME, REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.street", REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.streetNumber", REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.postalCode", REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.postalAddress", REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.country", REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
    }

    @Override
    protected BaseService getBaseService() {
        return memberClubService;
    }

    @Override
    protected boolean isNaturalKeyEqual(MemberClub savedEntity, MemberClub entityToCheck) {
        return savedEntity.getName().equals(entityToCheck.getName());
    }

    @Override
    protected void doRejectOfNaturalField(Errors errors, MemberClub entityToCheck) {
        errors.rejectValue(NAME_FIELD_NAME, "duplicate",
                MessageFormat.format("Duplicate golf club name",
                        entityToCheck.getName()));
    }
}
